﻿using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinForm_Mes.WorkingManagement.TeamSet
{
    public partial class TeamSetEmployeeForm : DevExpress.XtraEditors.XtraForm
    {
        // 定义委托和事件
        public delegate void TeamSetEmployeeDelegate();
        public event TeamSetEmployeeDelegate TeamSetEmployeeEvent;

        // 分页参数
        private int pageIndex = 1;
        private int pageSize = 20;
        private int total = 0;
        private int pageCount = 0;

        // 当前班组ID和名称
        private long teamSetId;
        private string teamSetName;

        // 无参构造函数
        public TeamSetEmployeeForm()
        {
            InitializeComponent();
        }

        // 带参数构造函数
        public TeamSetEmployeeForm(long id, string name)
        {
            InitializeComponent();
            teamSetId = id;
            teamSetName = name;
            this.Text = $"班组成员 - {teamSetName}";
        }

        private async void TeamSetEmployeeForm_Load_1(object sender, EventArgs e)
        {
            

            // 加载成员数据
            await LoadEmployeeData();
        }

        // 加载成员数据
        private async Task LoadEmployeeData()
        {
            try
            {
                // 显示加载提示
                gridControl1.DataSource = null;

                // 调用API获取成员列表
                var response = await HttpClientHelper.RequestUrl(
                    RequestType.get,
                    MethodGolab.SHOW_EMPDEFECT + $"?teamSetId={teamSetId}&PageIndex={pageIndex}&PageSize={pageSize}"
                );

                // 解析返回数据
                var result = JsonConvert.DeserializeObject<EmployeeList<EmployeeModel>>(response);

                if (result != null && result.code == 200)
                {
                    // 绑定数据到GridControl
                    gridControl1.DataSource = result.items;

                    // 更新分页信息
                    total = result.total;
                    pageCount = (int)Math.Ceiling((double)total / pageSize);

                        labelControl1.Text = $"共 {total} 条记录，当前第 {pageIndex}/{pageCount} 页";
                }
                else
                {
                    XtraMessageBox.Show($"查询失败：{result?.message ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"发生异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        // 刷新按钮点击事件
        private async void RefreshButton_Click(object sender, EventArgs e)
        {
            await LoadEmployeeData();
        }

        // 上一页按钮点击事件
        private async void PrevPageButton_Click(object sender, EventArgs e)
        {
            if (pageIndex > 1)
            {
                pageIndex--;
                await LoadEmployeeData();
            }
        }

        // 下一页按钮点击事件
        private async void NextPageButton_Click(object sender, EventArgs e)
        {
            if (pageIndex < pageCount)
            {
                pageIndex++;
                await LoadEmployeeData();
            }
        }

        // 移除员工按钮点击事件
        private void UpdateEmployee_Click(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            // 获取当前行
            int rowHandle = gridView1.FocusedRowHandle;
            if (rowHandle >= 0)
            {
                EmployeeModel employee = gridView1.GetRow(rowHandle) as EmployeeModel;
                if (employee != null)
                {
                    // 确认移除
                    if (XtraMessageBox.Show($"确定要移除成员 {employee.employeeName} 吗？", "确认",
                        MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        RemoveEmployee(employee.id);
                    }
                }
            }
        }

        // 移除员工方法
        private async void RemoveEmployee(long employeeId)
        {
            try
            {
                // 创建员工ID列表
                var employeeIds = new List<long> { employeeId };
                
                // 序列化为JSON数组
                string jsonData = JsonConvert.SerializeObject(employeeIds);
                
                // 构建URL，将teamSetId作为查询参数
                string url = $"{MethodGolab.POST_EMPUPDATERANGE}?teamSetId=0"; // 设置为0表示移除
                
                // 调用批量修改API
                var response = await HttpClientHelper.RequestUrl(
                    RequestType.post,
                    url,
                    jsonData
                );
                
                // 解析返回结果
                var result = JsonConvert.DeserializeObject<BaseResponse>(response);
                
                if (result != null && result.code == 200)
                {
                    XtraMessageBox.Show("成员移除成功！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    
                    // 触发事件通知父窗体刷新数据
                    if (TeamSetEmployeeEvent != null)
                    {
                        TeamSetEmployeeEvent.Invoke();
                    }
                    
                    // 刷新数据
                    await LoadEmployeeData();
                }
                else
                {
                    XtraMessageBox.Show($"成员移除失败：{result?.message ?? "未知错误"}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show($"发生异常：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void simpleButton2_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            Close();
        }

        private void gridControl1_Click(object sender, EventArgs e)
        {

        }
    }
}